package com.timmy.bledemo;

import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.content.Context;
import android.util.Log;

import com.clj.fastble.BleManager;
import com.clj.fastble.conn.BleCharacterCallback;
import com.clj.fastble.conn.BleGattCallback;
import com.clj.fastble.exception.BleException;
import com.clj.fastble.scan.ListScanCallback;
import com.clj.fastble.utils.HexUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * 蓝牙管理工具类
 */

public class BleUtils {

    private final String TAG = BleUtils.class.getSimpleName();
    private static BleUtils instances;
    private BleManager mBleManager;
    private List<DeviceInfo> mlist = new ArrayList<>();
    private String mac;

    //====================uuid
    private String uuid_service = "0000FFF0-0000-1000-8000-00805f9b34fb";
    private String uuid_notify = "0000FFF1-0000-1000-8000-00805f9b34fb";
    private String uuid_write = "0000FFF2-0000-1000-8000-00805f9b34fb";

    /**
     * false 华虹
     * true 博昌达
     */
    private boolean isFactory;

    public void setIsFactory(boolean isFactory) {
        this.isFactory = isFactory;

        if (isFactory) {
            uuid_service = "0000FFF0-0000-1000-8000-00805f9b34fb";
            uuid_notify = "0000FFF1-0000-1000-8000-00805f9b34fb";
            uuid_write = "0000FFF2-0000-1000-8000-00805f9b34fb";
        } else {
            uuid_service = "000056ff-0000-1000-8000-00805f9b34fb";
            uuid_notify = "000033f2-0000-1000-8000-00805f9b34fb";
            uuid_write = "000033f1-0000-1000-8000-00805f9b34fb";
        }
    }

    /**
     * 单例
     */
    public static BleUtils getInstance() {
        if (instances == null) {
            instances = new BleUtils();
        }
        return instances;
    }

    public BleUtils init(Context context) {

        if (mBleManager == null)
            mBleManager = new BleManager(context);

        return instances;
    }

    public String getMac() {
        return mac;
    }

    public void setMac(String mac) {
        this.mac = mac;
    }

    /**
     * 判断设备是否支持ble
     */
    public boolean isSupportBle() {
        return mBleManager.isSupportBle();
    }

    /**
     * 开启或者关闭蓝牙
     */
    public void enableBle() {
        if (mBleManager.isBlueEnable()) {
            mBleManager.disableBluetooth();
        } else {
            mBleManager.enableBluetooth();
        }
    }

    /**
     * 扫描设备
     *
     * @param callback
     */
    public void scanDevice(final BleScanCallback callback) {

        mlist.clear();

        mBleManager.scanDevice(new ListScanCallback(5000) {
            @Override
            public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
                super.onLeScan(device, rssi, scanRecord);
                //发现的设备
                DeviceInfo info = new DeviceInfo(device, rssi);

                String name = device.getName();
                if (name != null) {

                    // 过滤用户名
                    if (name.contains("MoLi") || name.contains("H001")) {
                        if (!mlist.contains(info)) {
                            mlist.add(info);
                        }
                    }
                }
            }

            @Override
            public void onDeviceFound(BluetoothDevice[] devices) {
                // 对发现的设备排序
                Collections.sort(mlist, new Comparator<DeviceInfo>() {
                    @Override
                    public int compare(DeviceInfo o1, DeviceInfo o2) {
                        return (o2.getRssi() - o1.getRssi());
                    }
                });
                callback.onBleScan(mlist);
            }
        });
    }

    /**
     * 连接设备
     */
    public void connectDevice(BluetoothDevice device, final BleConnectCallback callback) {
        mBleManager.connectDevice(device, false, new BleGattCallback() {
            @Override
            public void onNotFoundDevice() {
                Log.i(TAG, "没有发现设备~");
            }

            @Override
            public void onFoundDevice(BluetoothDevice device) {
                Log.i(TAG, "发现设备~");
            }

            @Override
            public void onConnectSuccess(BluetoothGatt gatt, int status) {
                Log.i(TAG, "连接成功！");
                gatt.discoverServices();
                callback.onConnectSuccess();
            }

            @Override
            public void onConnectFailure(BleException exception) {
                Log.e(TAG, "连接失败或连接中断：" + exception.toString());
                mac = "";
                mBleManager.handleException(exception);
                callback.onConnectFailure();
            }
        });
    }

    private boolean isNotify = true;


    /**
     * 开启通知
     */
    public void openNotify(final BleNotifyCallback callback) {

        mBleManager.notify(uuid_service, uuid_notify, new BleCharacterCallback() {
            @Override
            public void onSuccess(BluetoothGattCharacteristic characteristic) {

                if (isNotify) {
                    isNotify = false;
                    callback.onOntifyCallback();
                }

                byte[] value = characteristic.getValue();
                Log.d(TAG, "notify result： " + HexUtil.encodeHexStr(value));
            }

            @Override
            public void onFailure(BleException exception) {
                mBleManager.handleException(exception);
            }
        });
    }

    /**
     * 移除通知
     */
    public void closeNotify() {
        mBleManager.stopNotify(uuid_service, uuid_notify);
    }

    /**
     * 写入输入
     */
    public void write(byte[] data) {

        Log.i(TAG, "写入数据 " + HexUtil.encodeHexStr(data));

        mBleManager.writeDevice(uuid_service, uuid_write, data, new BleCharacterCallback() {
            @Override
            public void onSuccess(BluetoothGattCharacteristic characteristic) {
                Log.i(TAG, "onSuccess: 写入成功");
            }

            @Override
            public void onFailure(BleException exception) {
                Log.e(TAG, "onSuccess: 写入失败");
            }
        });
    }

    /**
     * 移除通知
     */
    public void closeWrite() {
        mBleManager.stopNotify(uuid_service, uuid_notify);
    }

    /**
     * 移除callback
     * 1 移除通知
     * 2 移除写入
     */
    public void removeCallbak(int count) {
        if (count == 1) {
            mBleManager.stopListenCharacterCallback(uuid_notify);
        } else if (count == 2) {
            mBleManager.stopListenCharacterCallback(uuid_write);
        }
    }

    /**
     * 断开蓝牙连接
     */
    public void closeBle() {
        closeNotify();
        mac = "";
        Log.i(TAG, "断开蓝牙连接");
        mBleManager.closeBluetoothGatt();
    }
}
